<?php (defined('BASEPATH')) OR exit('No direct script access allowed');


class Tools extends CI_Controller 
{

	function __construct()
	{
		parent::__construct();	
		$this->template->set_template('template/admin_template');
		if($this->general_model->loggedin("admin") == FALSE)
		{
			redirect('admin/users/login');
		}
	}
	
	function index()
	{
        
    }
	function widgets()
	{
		
        $data['breadcrumb'] = set_crumbs(array(current_url() => 'Widgets'));
        

        $data['widgets'] = $this->general_model->select("widgets");
           

        $this->template->content->view('admin/tool/widgets', $data);
		$this->template->publish();
	}
	function addwidget()
	{
		$data['breadcrumb'] = set_crumbs(array('tools/widgets' => 'Widgets', current_url() => 'Add Widget'));
		$this->form_validation->set_rules('title', 'Title', 'trim|required');
        $this->form_validation->set_rules('short_name', 'Short Name', 'trim|required|alpha_dash|max_length[50]|is_unique[widgets.short_name]');
		$this->form_validation->set_rules('widget_type', 'Widget Type', 'trim|required');
		$this->form_validation->set_rules('widget_content', 'Widget Content', 'trim|required');
        if ($this->form_validation->run() == TRUE)
        {
			$widgetdata=array(
				'title'=>$this->input->post('title'),
				'short_name'=>$this->input->post('short_name'),
				'widget_type'=>$this->input->post('widget_type'),
				'widget_content'=>addslashes($this->input->post('widget_content')),
				'widget_height'=>$this->input->post('widget_height'),
				'widget_width'=>$this->input->post('widget_width'),
				);
			$widgetid=$this->general_model->insert('widgets',$widgetdata);
			$this->session->set_flashdata('message', '<p class="success">widgets added Saved.</p>');
			if ($this->input->post('save_exit'))
			{
				redirect(ADMIN_PATH . "/tools/widgets");
			}
			else
			{
				redirect(ADMIN_PATH . "/tools/addwidget");
			}
		}

		$this->template->content->view('admin/tool/addwidgets', $data);
		$this->template->publish();

	}
	function editwidget()
	{
		$data['breadcrumb'] = set_crumbs(array('tools/widgets' => 'Widgets', current_url() => 'Edit Widget'));
		$widgetid=$this->uri->segment(4);
		
		$this->form_validation->set_rules('title', 'Title', 'trim|required');
        $this->form_validation->set_rules('short_name', 'Short Name', 'trim|required|alpha_dash|max_length[50]');
		$this->form_validation->set_rules('widget_type', 'Widget Type', 'trim|required');
		$this->form_validation->set_rules('widget_content', 'Widget Content', 'trim|required');
        if ($this->form_validation->run() == TRUE)
        {
			$widgetdata=array(
				'title'=>$this->input->post('title'),
				'short_name'=>$this->input->post('short_name'),
				'widget_type'=>$this->input->post('widget_type'),
				'widget_content'=>addslashes($this->input->post('widget_content')),
				'widget_height'=>$this->input->post('widget_height'),
				'widget_width'=>$this->input->post('widget_width'),
				);
			$widgetid=$this->general_model->update('widgets',$widgetdata,'id = '.$widgetid);
			$this->session->set_flashdata('message', '<p class="success">widgets updated Saved.</p>');
			if ($this->input->post('save_exit'))
			{
				redirect(ADMIN_PATH . "/tools/widgets");
			}
			else
			{
				redirect(ADMIN_PATH . "/tools/addwidget");
			}
		}
		$data['widgets']=$this->general_model->select_val("widgets","*","id = ".$widgetid);
		$this->template->content->view('admin/tool/editwidgets', $data);
		$this->template->publish();

	}
	public function deletewidget()
	{
		if ($this->input->post('selected'))
        {
            $selected = $this->input->post('selected');
        }
        else
        {
            $selected = (array) $this->uri->segment(5);
        }
		$this->general_model->delete_rows('widgets','id',$selected);
		$this->session->set_flashdata('message', '<p class="success">Widget deleted Successfully.</p>');
		redirect(ADMIN_PATH . "/tools/widgets");
	}
	function theme_editor()
	{
        $data['breadcrumb'] = set_crumbs(array(current_url() => 'Theme Editor'));
		$theme_dir = BASE_URL ;
		//echo $theme_dir;
		$data['files_found'] = TRUE;
        $data['file_readable'] = TRUE;
        $data['file_writable'] = TRUE;

        $this->load->helper('file');
		
		
        $this->template->stylesheet->add(array('assets/admin/css/theme_editor.css')); 
		$this->template->javascript->add(array('assets/admin/js/codemirror-2.25/lib/codemirror.js',
												'assets/admin/js/codemirror-2.25/mode/xml/xml.js',
												'assets/admin/js/codemirror-2.25/mode/javascript/javascript.js',
												'assets/admin/js/codemirror-2.25/mode/css/css.js',
												'assets/admin/js/codemirror-2.25/mode/clike/clike.js',
												'assets/admin/js/codemirror-2.25/mode/php/php.js',
        ));
		$this->template->stylesheet->add(array('assets/admin/js/codemirror-2.25/lib/codemirror.css'
        ));
		$data['templates'] = $this->get_theme_files('{php, html}', APPPATH.'views/template');
		$data['cmsviews'] = $this->get_theme_files('{php, html}', APPPATH.'views/front');
		$data['adminviews'] = $this->get_theme_files('{php, html}', APPPATH.'views/admin');
		$data['widgets'] = $this->get_theme_files('{php, html}', APPPATH.'views/widgets');
		$data['cmsstylesheets'] = $this->get_theme_files('css','assets/front/css');
		
		$data['adminstylesheets'] = $this->get_theme_files('css','assets/admin/css');
        $data['cmsjavascripts'] = $this->get_theme_files('js','assets/front/js');
		$data['adminjavascripts'] = $this->get_theme_files('js','assets/admin/js');
		if ($hash = $this->uri->segment(4))
        {
            $data['file'] = $file = url_base64_decode($hash);
			
        }
        else
        {
            // Check if assets/css/style.css exists and load it first if no other file specified
            if (isset($data['cmsstylesheets']['style.css']))
            {
                $data['file'] = $file = url_base64_decode($data['cmsstylesheets']['style.css']['hash']);
				
            }
            else
            {
				
                // There was no style.css so load first file found if any
                foreach (array('cmsstylesheets','adminstylesheets','cmsjavascripts','adminjavascripts', 'templates', 'cmsviews','adminviews','widgets', 'javascripts') as $theme_type)
                {
                    if ( ! empty($data[$theme_type]))
                    {

                        $file_array = current($data[$theme_type]);
                        $data['file'] = $file = url_base64_decode($file_array['hash']);
						
                        break;
                    }
                }
				
            }
        }
		 if ( ! empty($file))
        {
			
            // Check if the file exists and is readable
            if (is_readable($file))
            {
				
                // Read the file
                $data['code'] = read_file($file);
				//print_r($data['code']);
                // Check if file is writable
                if ( ! is_writable($file))
                {
                    $data['file_writable'] = FALSE;
                }

                // Determine CodeMirror mode from extension
                switch (pathinfo($file, PATHINFO_EXTENSION))
                {
                    case "css":
                        $data['mode'] = 'text/css';
                        break;
                    case "js":
                        $data['mode'] = 'text/javascript';
                        break;
                    default:
                        $data['mode'] = 'application/x-httpd-php';
                        break;
                }
            }
            else
            {
                // Flag file as not found or not readable
                $data['file_readable'] = FALSE;
            }
        }
        else
        {
            // No theme files were found
            $data['files_found'] = FALSE;
        }
		// Form validation
        $this->form_validation->set_rules('code', 'Text Area', 'required');
		
        if ($this->form_validation->run() == TRUE)
        {
            // Write post to file
            if (write_file($file, $this->input->post('code')))
            {
                $this->session->set_flashdata('message', '<p class="success">File saved successfully.</p>');
            }
            else
            {
                $this->session->set_flashdata('message', '<p class="error">Unable to write to file.</p>');
            }

            redirect(current_url());
        }

		$this->template->content->view('admin/tool/theme_editor', $data);
		$this->template->publish();
    }
	function get_theme_files($extension = 'php', $directory = '/')
    {
        $theme_dir = BASE_URL;
        $pattern = $theme_dir . trim($directory, '/') . '/*.' . $extension;
		//echo $pattern;
        $file_array = array();
        //$files = glob_recursive($pattern, GLOB_BRACE);
		$this->load->helper('file');
		//echo $directory."<br>";
		$files = get_dir_file_info($directory,$top_level_only = TRUE);
		/*echo "<pre>";
		print_r($files);*/
        foreach ($files as $file)
        {
            //$relative_path = str_replace(dirname($pattern) . '/', '', $file['relative_path']);
			$relative_path = $file['name'];
			//echo $relative_path;
           // $theme_path = str_replace($theme_dir, '', $file);
		   $theme_path = $file['relative_path'].'/'.$file['name'];

            $file_array[$relative_path] = array(
                'hash'          => url_base64_encode($theme_path), // relative to the current theme's root directory
                'theme_path'    => $theme_path,
                'relative_path' => $relative_path,
                'title'         => ucwords(str_replace(array('_', '-'), ' ', $file['name'])),
            );
        }

        return $file_array;
    }
}

